﻿using BusinessManage.Common;
using CPFrameWork.Global;
using CPFrameWork.Utility;
using CPFrameWork.Utility.DbOper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessManage.OrganizeInfo
{
    public class OrganizeDataSyncController : CPWebApiBaseController
    {
        [HttpGet]
        //
        public string SyncOrganzeData()
        {
            return SyncDeptInfo();
        }
        DbHelper _helper = new DbHelper("CPYKWL", CPAppContext.CurDbType());
        DbHelper _dephelper = new DbHelper("CPOrganIns", CPAppContext.CurDbType());
        private readonly Logger log = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 同步组织机构
        /// </summary>
        public string SyncDeptInfo()
        {
            //1、获取url、token值
            string Url = CPUtils.Configuration.GetSection("AppSettings")["Url"];
            string tokenId = CPUtils.Configuration.GetSection("AppSettings")["TokenId"];

            //获取时间戳
            string currentTimeStamp = TimeStamp.GetTheTimeStamp(true, DateTime.UtcNow);

            //2、参数
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("timestamp", currentTimeStamp);
            sParaTemp.Add("method", "branch.apilist");
            sParaTemp.Add("format", "json");
            sParaTemp.Add("sign_type", "MD5");
            sParaTemp.Add("v", "v1");

            //3、调取生产签名的算法  得到sign值
            string signString = "";
            signString = CreateSign.CreateSignString(sParaTemp, tokenId);
            SortedDictionary<string, string> allPara = new SortedDictionary<string, string>();
            allPara = sParaTemp;
            allPara.Add("sign", signString);
            //得到序列化的参数值,拼接成"key1=value1&key2=value2"形式
            string data = BusinessManage.Common.wphttppost.datapost(allPara);
            log.Info("开始从接口获取部门信息，请求参数为：" + data);

            //4、获取接口中返回的数据
            string result = "";
            try
            {
                result = BusinessManage.Common.wphttppost.Post(data, Url, 6);
                //-------从接口获取数据成功，写入日志
                log.Info("调用部门信息接口成功，获取数据为：" + result);
            }
            catch (Exception ex)
            {
                //-------从接口获取数据失败，写入日志
                log.Info("从接口获取部门信息失败，失败信息为：{0}\n  详细信息为{1}   \n ", ex.Message, ex.StackTrace);
                return "从接口获取数据失败 ：" + ex.Message;
            }

            try
            {
                JObject jdeptResult = (JObject)JsonConvert.DeserializeObject(result);
                if (jdeptResult["error"].ToString().Equals(""))
                {
                    if (string.IsNullOrEmpty(jdeptResult["result"].ToString()))
                    {
                        log.Info("未获取需要同步的组织机构数据。");
                        return "未获取需要同步的组织机构数据";
                    }
                    JArray deptinfo = (JArray)jdeptResult["result"];
                    if (deptinfo.Count != 0)
                    {
                        StringBuilder deptlist_first_String = new StringBuilder();    //原始表：一级组织机构sql语句
                        StringBuilder deptlist_other_String = new StringBuilder();   //原始表：二级、三级、四级组织机构sql语句

                        StringBuilder deptlist_first_UpdateString = new StringBuilder();    //更新系统组织机构表：一级组织机构sql语句
                        StringBuilder deptlist_other_UpdateString = new StringBuilder();    //更新系统组织机构表：二级、三级、四级组织机构sql语句

                        DateTime sychTime = DateTime.Now;
                        deptlist_first_UpdateString.Append("SET IDENTITY_INSERT CP_Dep ON;");
                        deptlist_other_UpdateString.Append("SET IDENTITY_INSERT CP_Dep ON;");
                        //生成一级组织机构SQL
                        var deptlist_first = deptinfo.AsEnumerable().Where(t => t["branch_type"].ToString() == "1").ToList();
                        foreach (var item in deptlist_first)
                        {
                            string id = item["id"].ToString();
                            string code = item["code"].ToString();
                            string name = item["name"].ToString();
                            string parent_code = item["parent_code"].ToString();
                            string createtime = item["createtime"].ToString();
                            string office_id = item["office_id"].ToString();
                            string parent_ids = item["parent_ids"].ToString();
                            string branch_type = item["branch_type"].ToString();
                            string parent_id = item["parent_id"].ToString();
                            string is_sap_start = item["is_sap_start"].ToString();
                            //拼接插入原始表sql--一级
                            deptlist_first_String.Append("insert into O_sysuser_branch (id,code,name,parent_code,createtime,office_id,parent_ids,branch_type,parent_id,is_sap_start,syntime) values(");
                            deptlist_first_String.Append("'" + id + "',");
                            deptlist_first_String.Append("'" + code + "',");
                            deptlist_first_String.Append("'" + name + "',");
                            deptlist_first_String.Append("'" + parent_code + "',");
                            deptlist_first_String.Append("'" + createtime + "',");
                            deptlist_first_String.Append("'" + office_id + "',");
                            deptlist_first_String.Append("'" + parent_ids + "',");
                            deptlist_first_String.Append("'" + branch_type + "',");
                            deptlist_first_String.Append("'" + parent_id + "',");
                            deptlist_first_String.Append("'" + is_sap_start + "',");
                            deptlist_first_String.Append("'" + sychTime + "'");
                            deptlist_first_String.Append(");");
                            //拼接更新物流系统组织机构表sql--一级
                            deptlist_first_UpdateString.Append("IF EXISTS (select * from CP_Dep where DepId='" + id + "') update CP_Dep set DepName='" + name + "',DepShortCode='" + code + "',ParentId='-1',DepType='" + branch_type + "',DepState='1' where DepId='" + id + "'");
                            deptlist_first_UpdateString.Append(" else insert into CP_Dep (DepId,DepName,DepShortCode,ParentId,DepType,DepState) values(");
                            deptlist_first_UpdateString.Append("'" + id + "',");
                            deptlist_first_UpdateString.Append("'" + name + "',");
                            deptlist_first_UpdateString.Append("'" + code + "',");
                            deptlist_first_UpdateString.Append("'-1',");
                            deptlist_first_UpdateString.Append("'" + branch_type + "',");
                            deptlist_first_UpdateString.Append("'1'");
                            deptlist_first_UpdateString.Append(");");
                        }
                        //生成二级、三级、四级组织机构SQL
                        var deptlist_other = deptinfo.AsEnumerable().Where(t => t["branch_type"].ToString() == "2" || t["branch_type"].ToString() == "3" || t["branch_type"].ToString() == "4").ToList();
                        foreach (var item in deptlist_other)
                        {
                            string id = item["id"].ToString();
                            string code = item["code"].ToString();
                            string name = item["name"].ToString();
                            string parent_code = item["parent_code"].ToString();
                            string createtime = item["createtime"].ToString();
                            string office_id = item["office_id"].ToString();
                            string parent_ids = item["parent_ids"].ToString();
                            string branch_type = item["branch_type"].ToString();
                            string parent_id = item["parent_id"].ToString();
                            string is_sap_start = item["is_sap_start"].ToString();
                            //拼接插入原始表sql--二级、三级、四级
                            deptlist_other_String.Append("insert into O_sysuser_branch (id,code,name,parent_code,createtime,office_id,parent_ids,branch_type,parent_id,is_sap_start,syntime) values(");
                            deptlist_other_String.Append("'" + id + "',");
                            deptlist_other_String.Append("'" + code + "',");
                            deptlist_other_String.Append("'" + name + "',");
                            deptlist_other_String.Append("'" + parent_code + "',");
                            deptlist_other_String.Append("'" + createtime + "',");
                            deptlist_other_String.Append("'" + office_id + "',");
                            deptlist_other_String.Append("'" + parent_ids + "',");
                            deptlist_other_String.Append("'" + branch_type + "',");
                            deptlist_other_String.Append("'" + parent_id + "',");
                            deptlist_other_String.Append("'" + is_sap_start + "',");
                            deptlist_other_String.Append("'" + sychTime + "'");
                            deptlist_other_String.Append(");");
                            //拼接更新物流系统组织机构表sql--二级、三级、四级
                            deptlist_other_UpdateString.Append("IF EXISTS (select * from CP_Dep where DepId='" + id + "') update CP_Dep set DepName='" + name + "',DepShortCode='" + code + "',ParentId='" + parent_id + "',DepType='" + branch_type + "',DepState='1' where DepId='" + id + "'");
                            deptlist_other_UpdateString.Append(" else insert into CP_Dep (DepId,DepName,DepShortCode,ParentId,DepType,DepState) values(");
                            deptlist_other_UpdateString.Append("'" + id + "',");
                            deptlist_other_UpdateString.Append("'" + name + "',");
                            deptlist_other_UpdateString.Append("'" + code + "',");
                            deptlist_other_UpdateString.Append("'" + parent_id + "',");
                            deptlist_other_UpdateString.Append("'" + branch_type + "',");
                            deptlist_other_UpdateString.Append("'1'");
                            deptlist_other_UpdateString.Append(");");
                        }

                        deptlist_first_UpdateString.Append("SET IDENTITY_INSERT CP_Dep OFF ");
                        deptlist_other_UpdateString.Append("SET IDENTITY_INSERT CP_Dep OFF ");
                       
                        try
                        {
                            //执行sql，同步至原始组织机构表
                            _helper.ExecuteNonQuery(deptlist_first_String.ToString()); //一级组织机构
                            _helper.ExecuteNonQuery(deptlist_other_String.ToString()); //二级、三级、四级组织机构
                            //执行sql，更新物流系统的组织机构表
                            _dephelper.ExecuteNonQuery(deptlist_first_UpdateString.ToString());
                            _dephelper.ExecuteNonQuery(deptlist_other_UpdateString.ToString());
                            
                            log.Info("组织机构同步成功。");
                            return "同步成功！";
                        }
                        catch (Exception ex)
                        {
                            log.Error(string.Format("数据入库时执行失败! 错误信息为：{0}\n 详细信息为:{1} \n ", ex.Message, ex.StackTrace));
                            return "组织机构同步失败。";
                        }
                    }
                    else
                    {
                        //获取数据列表为空
                        return "未获取数据";
                    }
                }
                else
                {
                    //数据获取有误，写入日志
                    JToken errorResult = jdeptResult["error"];
                    string errorMessage = errorResult["message"].ToString();
                    log.Error("从接口获取部门信息失败，返回数据为：" + result);
                    return "从接口获取部门信息失败，错误信息为：" + errorMessage;                    
                }
            }
            catch (Exception ex)
            {
                //-------从接口获取数据失败，写入日志
                log.Error(string.Format("部门信息数据解析失败，失败信息为：{0}\n  详细信息为{1}   \n 服务返回数据为{2}", ex.Message, ex.StackTrace, result));
                return "部门信息数据解析失败 ：" + ex.Message;
            }
        }
    }
}
